// 用户管理模块 - 用户认证、资料、私信等功能

// 全局用户相关变量
let currentUser = null;
let unreadMessagesCount = 0;
let unreadPollingTimer = null;

// ========== 用户认证相关函数 ==========

// 检查用户登录状态
function checkUserStatus() {
    fetch('/api/user')
        .then(response => response.json())
        .then(data => {
            if (data.logged_in) {
                currentUser = data;
                showLoggedInState(data.username);
            } else {
                showLoggedOutState();
            }
        })
        .catch(error => {
            console.error('Error checking user status:', error);
            showLoggedOutState();
        });
}

// 显示已登录状态
function showLoggedInState(username) {
    document.getElementById('notLoggedIn').classList.add('d-none');
    document.getElementById('loggedIn').classList.remove('d-none');
    const usernameElement = document.getElementById('currentUsername');
    usernameElement.textContent = username;
    // 添加点击事件，显示当前用户的个人资料
    usernameElement.onclick = function() {
        if (currentUser && currentUser.user_id) {
            showUserProfile(currentUser.user_id);
        }
    };
    document.getElementById('addCommentSection').classList.remove('d-none');

    // 启动未读私信轮询
    startUnreadPolling();
}

// 显示未登录状态
function showLoggedOutState() {
    document.getElementById('notLoggedIn').classList.remove('d-none');
    document.getElementById('loggedIn').classList.add('d-none');
    document.getElementById('addCommentSection').classList.add('d-none');
    currentUser = null;

    // 停止未读私信轮询并隐藏徽标
    stopUnreadPolling();
    const badge = document.getElementById('unreadBadge');
    if (badge) {
        badge.classList.add('d-none');
        badge.textContent = '0';
    }
}

// 处理登录
function handleLogin(e) {
    e.preventDefault();
    
    const username = document.getElementById('loginUsername').value.trim();
    const password = document.getElementById('loginPassword').value.trim();
    
    if (!username || !password) {
        showError('loginError', '请填写用户名和密码');
        return;
    }
    
    fetch('/api/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, password })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            bootstrap.Modal.getInstance(document.getElementById('loginModal')).hide();
            checkUserStatus();
            document.getElementById('loginForm').reset();
            hideError('loginError');
        } else {
            showError('loginError', data.error);
        }
    })
    .catch(error => {
        console.error('Login error:', error);
        showError('loginError', '登录失败，请重试');
    });
}

// 处理注册
function handleRegister(e) {
    e.preventDefault();
    
    const username = document.getElementById('registerUsername').value.trim();
    const email = document.getElementById('registerEmail').value.trim();
    const password = document.getElementById('registerPassword').value.trim();
    
    if (!username || !email || !password) {
        showError('registerError', '请填写所有字段');
        return;
    }
    
    if (password.length < 6) {
        showError('registerError', '密码至少需要6个字符');
        return;
    }
    
    fetch('/api/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, email, password })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            bootstrap.Modal.getInstance(document.getElementById('registerModal')).hide();
            checkUserStatus();
            document.getElementById('registerForm').reset();
            hideError('registerError');
        } else {
            showError('registerError', data.error);
        }
    })
    .catch(error => {
        console.error('Register error:', error);
        showError('registerError', '注册失败，请重试');
    });
}

// 处理退出登录
function handleLogout() {
    fetch('/api/logout', {
        method: 'POST'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showLoggedOutState();
            showSearchPage();
            // 刷新页面回到首页
            setTimeout(() => {
                window.location.reload();
            }, 500);
        }
    })
    .catch(error => {
        console.error('Logout error:', error);
    });
}

// ========== 用户资料相关函数 ==========

// 显示用户资料
function showUserProfile(userId) {
    // 显示模态框
    const userModal = new bootstrap.Modal(document.getElementById('userProfileModal'));
    userModal.show();
    
    // 重置表单
    toggleEmailForm(false);
    togglePasswordForm(false);
    
    // 显示加载状态
    document.getElementById('userProfileContainer').innerHTML = `
        <div class="text-center p-4">
            <div class="spinner-border text-primary mb-3" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mb-0">正在加载用户信息，请稍候...</p>
        </div>
    `;
    
    // 获取用户信息
    fetch(`/api/user/${userId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取用户信息失败');
            }
            return response.json();
        })
        .then(data => {
            displayUserProfile(data);
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('userProfileContainer').innerHTML = `
                <div class="alert alert-danger">
                    <i class="bi bi-exclamation-triangle me-2"></i>
                    加载用户信息失败: ${error.message || '未知错误'}
                </div>
            `;
        });
}

// 显示用户资料
function displayUserProfile(userData) {
    const container = document.getElementById('userProfileContainer');
    const footer = document.getElementById('userProfileFooter');
    
    if (!userData || userData.error) {
        container.innerHTML = `
            <div class="alert alert-danger">
                <i class="bi bi-exclamation-triangle me-2"></i>
                ${userData.error || '获取用户信息失败'}
            </div>
        `;
        return;
    }
    
    // 设置模态框标题
    document.getElementById('userProfileModalLabel').textContent = `${userData.username} 的个人资料`;
    
    // 生成用户信息HTML
    let userHtml = `
        <div class="user-profile">
            <div class="text-center mb-4">
                <div class="avatar-placeholder mb-3">
                    <i class="bi bi-person-circle" style="font-size: 4rem;"></i>
                </div>
                <h4>${userData.username}</h4>
                <p class="text-muted">
                    <span class="badge bg-${userData.role === 'admin' ? 'danger' : 'secondary'}">${userData.role === 'admin' ? '管理员' : '普通用户'}</span>
                </p>
            </div>
            
            <div class="user-stats d-flex justify-content-around mb-4">
                <div class="text-center">
                    <h5>${userData.content_count}</h5>
                    <p class="text-muted">内容</p>
                </div>
                <div class="text-center">
                    <h5>${userData.comment_count}</h5>
                    <p class="text-muted">评论</p>
                </div>
            </div>
            
            <div class="user-info">
                <p><strong>注册时间:</strong> ${formatDate(userData.created_at)}</p>
    `;
    
    // 如果是当前用户，显示邮箱和修改选项
    if (userData.is_current_user) {
        userHtml += `
                <p><strong>邮箱:</strong> ${userData.email}</p>
            </div>
            
            <div class="user-actions mt-4">
                <button class="btn btn-outline-primary me-2" onclick="toggleEmailForm(true)">
                    <i class="bi bi-envelope me-1"></i>修改邮箱
                </button>
                <button class="btn btn-outline-primary" onclick="togglePasswordForm(true)">
                    <i class="bi bi-key me-1"></i>修改密码
                </button>
            </div>
        `;
        
        // 修改底部按钮
        footer.innerHTML = `
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
        `;
    } else {
        userHtml += `
            </div>
            
            <div class="user-actions mt-4">
                <button class="btn btn-primary" onclick="showSendMessageForm('${userData.id}', '${userData.username}')">
                    <i class="bi bi-envelope me-1"></i>发送私信
                </button>
            </div>
        `;
        
        // 修改底部按钮
        footer.innerHTML = `
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
        `;
    }
    
    container.innerHTML = userHtml;
}

// 切换邮箱修改表单显示
function toggleEmailForm(show) {
    const profileContainer = document.getElementById('userProfileContainer');
    const emailForm = document.getElementById('updateEmailForm');
    const passwordForm = document.getElementById('updatePasswordForm');
    
    if (show) {
        profileContainer.classList.add('d-none');
        emailForm.classList.remove('d-none');
        passwordForm.classList.add('d-none');
        document.getElementById('newEmail').focus();
        hideError('emailUpdateError');
    } else {
        profileContainer.classList.remove('d-none');
        emailForm.classList.add('d-none');
        document.getElementById('newEmail').value = '';
    }
}

// 切换密码修改表单显示
function togglePasswordForm(show) {
    const profileContainer = document.getElementById('userProfileContainer');
    const emailForm = document.getElementById('updateEmailForm');
    const passwordForm = document.getElementById('updatePasswordForm');
    
    if (show) {
        profileContainer.classList.add('d-none');
        passwordForm.classList.remove('d-none');
        emailForm.classList.add('d-none');
        document.getElementById('currentPassword').focus();
        hideError('passwordUpdateError');
    } else {
        profileContainer.classList.remove('d-none');
        passwordForm.classList.add('d-none');
        document.getElementById('currentPassword').value = '';
        document.getElementById('newPassword').value = '';
        document.getElementById('confirmPassword').value = '';
    }
}

// 更新邮箱
function updateEmail() {
    const newEmail = document.getElementById('newEmail').value.trim();
    
    if (!newEmail) {
        showError('emailUpdateError', '请输入新邮箱地址');
        return;
    }
    
    // 验证邮箱格式
    const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (!emailPattern.test(newEmail)) {
        showError('emailUpdateError', '邮箱格式不正确');
        return;
    }
    
    fetch('/api/user/update', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email: newEmail })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 更新成功，刷新用户信息
            toggleEmailForm(false);
            showUserProfile(currentUser.user_id);
        } else {
            showError('emailUpdateError', data.error || '更新邮箱失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showError('emailUpdateError', '更新邮箱失败，请重试');
    });
}

// 更新密码
function updatePassword() {
    const currentPassword = document.getElementById('currentPassword').value.trim();
    const newPassword = document.getElementById('newPassword').value.trim();
    const confirmPassword = document.getElementById('confirmPassword').value.trim();
    
    if (!currentPassword || !newPassword || !confirmPassword) {
        showError('passwordUpdateError', '请填写所有密码字段');
        return;
    }
    
    if (newPassword.length < 6) {
        showError('passwordUpdateError', '新密码至少需要6个字符');
        return;
    }
    
    if (newPassword !== confirmPassword) {
        showError('passwordUpdateError', '两次输入的新密码不一致');
        return;
    }
    
    fetch('/api/user/update', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
            current_password: currentPassword,
            password: newPassword
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 更新成功，关闭表单
            togglePasswordForm(false);
            alert('密码已成功更新');
        } else {
            showError('passwordUpdateError', data.error || '更新密码失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showError('passwordUpdateError', '更新密码失败，请重试');
    });
}

// ========== 私信相关函数 ==========

// 显示发送私信表单
function showSendMessageForm(userId, username) {
    // 关闭用户资料模态框
    const userModal = bootstrap.Modal.getInstance(document.getElementById('userProfileModal'));
    if (userModal) {
        userModal.hide();
    }
    
    // 设置收件人信息
    document.getElementById('messageRecipient').value = username;
    document.getElementById('sendMessageForm').dataset.recipientId = userId;
    
    // 清空表单
    document.getElementById('messageSubject').value = '';
    document.getElementById('messageContent').value = '';
    hideError('messageError');
    hideError('messageSuccess');
    
    // 显示发送私信模态框
    const messageModal = new bootstrap.Modal(document.getElementById('sendMessageModal'));
    messageModal.show();
    
    // 聚焦到主题输入框
    setTimeout(() => {
        document.getElementById('messageSubject').focus();
    }, 500);
}

// 发送私信
function sendPrivateMessage() {
    const recipientId = parseInt(document.getElementById('sendMessageForm').dataset.recipientId);
    const subject = document.getElementById('messageSubject').value.trim();
    const content = document.getElementById('messageContent').value.trim();
    
    if (!recipientId || isNaN(recipientId)) {
        showError('messageError', '收件人信息无效');
        return;
    }
    
    if (!subject) {
        showError('messageError', '请输入消息主题');
        return;
    }
    
    if (!content) {
        showError('messageError', '请输入消息内容');
        return;
    }
    
    // 隐藏之前的错误和成功消息
    hideError('messageError');
    hideError('messageSuccess');
    
    console.log('发送私信:', { recipient_id: recipientId, subject, content });
    
    fetch('/api/messages', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            recipient_id: recipientId,
            subject: subject,
            content: content
        })
    })
    .then(response => response.json())
    .then(data => {
        console.log('私信发送响应:', data);
        if (data.success) {
            // 显示成功消息
            document.getElementById('messageSuccess').textContent = '私信发送成功！';
            document.getElementById('messageSuccess').classList.remove('d-none');
            
            // 清空表单
            document.getElementById('messageSubject').value = '';
            document.getElementById('messageContent').value = '';
            
            // 2秒后关闭模态框
            setTimeout(() => {
                const messageModal = bootstrap.Modal.getInstance(document.getElementById('sendMessageModal'));
                if (messageModal) {
                    messageModal.hide();
                }
            }, 2000);
        } else {
            showError('messageError', data.error || '发送私信失败');
        }
    })
    .catch(error => {
        console.error('发送私信错误:', error);
        showError('messageError', '发送私信失败，请重试');
    });
}

// 显示私信列表
function showMessages() {
    const messagesModal = new bootstrap.Modal(document.getElementById('messagesModal'));
    messagesModal.show();
    
    // 加载收到的私信
    loadMessages('received');
    
    // 仅绑定一次标签切换事件（通过 dataset 标记避免重复）
    const receivedTab = document.getElementById('received-tab');
    const sentTab = document.getElementById('sent-tab');
    if (receivedTab && !receivedTab.dataset.bound) {
        receivedTab.addEventListener('click', () => loadMessages('received'));
        receivedTab.dataset.bound = '1';
    }
    if (sentTab && !sentTab.dataset.bound) {
        sentTab.addEventListener('click', () => loadMessages('sent'));
        sentTab.dataset.bound = '1';
    }
}

// 加载私信列表
function loadMessages(type) {
    const containerId = type === 'received' ? 'receivedMessagesList' : 'sentMessagesList';
    const container = document.getElementById(containerId);
    
    // 显示加载状态
    container.innerHTML = `
        <div class="text-center p-4">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2">正在加载私信...</p>
        </div>
    `;
    
    fetch(`/api/messages?type=${type}`)
        .then(response => response.json())
        .then(data => {
            displayMessages(data.messages, containerId, type);
        })
        .catch(error => {
            console.error('加载私信失败:', error);
            container.innerHTML = `
                <div class="alert alert-danger">
                    <i class="bi bi-exclamation-triangle me-2"></i>
                    加载私信失败: ${error.message || '未知错误'}
                </div>
            `;
        });
}

// 显示私信列表
function displayMessages(messages, containerId, type) {
    const container = document.getElementById(containerId);
    
    if (!messages || messages.length === 0) {
        container.innerHTML = `
            <div class="alert alert-info">
                <i class="bi bi-info-circle me-2"></i>
                ${type === 'received' ? '暂无收到的私信' : '暂无发送的私信'}
            </div>
        `;
        return;
    }
    
    let messagesHtml = '';
    messages.forEach(message => {
        const isUnread = type === 'received' && !message.is_read;
        const otherUser = type === 'received' ? message.sender_username : message.recipient_username;
        
        messagesHtml += `
            <div class="message-item border rounded p-3 mb-3 ${isUnread ? 'border-primary bg-light' : ''}">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div>
                        <h6 class="mb-1 ${isUnread ? 'fw-bold' : ''}">${message.subject}</h6>
                        <small class="text-muted">
                            ${type === 'received' ? '来自' : '发送给'}: 
                            <a href="javascript:void(0)" onclick="showUserProfile(${type === 'received' ? message.sender_id : message.recipient_id})" class="user-link">${otherUser}</a>
                        </small>
                    </div>
                    <div class="text-end">
                        <small class="text-muted">${formatDate(message.created_at)}</small>
                        ${isUnread ? '<span class="badge bg-primary ms-2">未读</span>' : ''}
                    </div>
                </div>
                <div class="message-content">
                    <p class="mb-2">${message.content}</p>
                </div>
                <div class="message-actions d-flex justify-content-end">
                    ${type === 'received' && !message.is_read ? 
                        `<button class="btn btn-sm btn-outline-primary me-2" onclick="markMessageRead(${message.id})">
                            <i class="bi bi-check me-1"></i>标记已读
                        </button>` : ''
                    }
                    ${type === 'received' ? 
                        `<button class="btn btn-sm btn-link reply-button" onclick="replyToMessage('${otherUser}', ${type === 'received' ? message.sender_id : message.recipient_id}, '${message.subject}')">
                            <i class="bi bi-reply me-1"></i>回复
                        </button>` : ''
                    }
                </div>
            </div>
        `;
    });
    
    container.innerHTML = messagesHtml;
}

// 标记私信为已读
function markMessageRead(messageId) {
    fetch(`/api/messages/${messageId}/read`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 重新加载收到的私信列表
            loadMessages('received');
            // 刷新未读徽标
            fetchUnreadCount();
        } else {
            alert('标记已读失败: ' + (data.error || '未知错误'));
        }
    })
    .catch(error => {
        console.error('标记已读失败:', error);
        alert('标记已读失败，请重试');
    });
}

// 回复私信
function replyToMessage(username, userId, originalSubject) {
    // 关闭私信列表模态框
    const messagesModal = bootstrap.Modal.getInstance(document.getElementById('messagesModal'));
    if (messagesModal) {
        messagesModal.hide();
    }
    
    // 显示发送私信表单，并预填回复信息
    setTimeout(() => {
        showSendMessageForm(userId, username);
        // 设置回复主题
        const subject = originalSubject.startsWith('Re: ') ? originalSubject : 'Re: ' + originalSubject;
        document.getElementById('messageSubject').value = subject;
    }, 500);
}

// ========== 未读私信轮询功能 ==========

// 未读私信：获取数量
function fetchUnreadCount() {
    if (!currentUser) return;
    fetch('/api/messages/unread_count')
        .then(response => response.json())
        .then(data => {
            if (data && typeof data.unread === 'number') {
                unreadMessagesCount = data.unread;
                updateUnreadBadge();
            }
        })
        .catch(error => {
            console.error('获取未读私信数量失败:', error);
        });
}

// 更新未读徽标
function updateUnreadBadge() {
    const badge = document.getElementById('unreadBadge');
    if (!badge) return;
    
    if (unreadMessagesCount > 0) {
        badge.classList.remove('d-none');
        badge.textContent = unreadMessagesCount > 99 ? '99+' : unreadMessagesCount.toString();
    } else {
        badge.classList.add('d-none');
        badge.textContent = '0';
    }
}

// 未读私信：启动/停止轮询
function startUnreadPolling() {
    stopUnreadPolling();
    fetchUnreadCount();
    unreadPollingTimer = setInterval(fetchUnreadCount, 15000);
}

function stopUnreadPolling() {
    if (unreadPollingTimer) {
        clearInterval(unreadPollingTimer);
        unreadPollingTimer = null;
    }
}



// ========== 事件监听器绑定 ==========

document.addEventListener('DOMContentLoaded', function() {
    // 检查用户登录状态
    checkUserStatus();
    
    // 用户认证相关事件绑定
    document.getElementById('loginButton').addEventListener('click', () => {
        new bootstrap.Modal(document.getElementById('loginModal')).show();
    });
    document.getElementById('registerButton').addEventListener('click', () => {
        new bootstrap.Modal(document.getElementById('registerModal')).show();
    });
    document.getElementById('logoutButton').addEventListener('click', handleLogout);
    document.getElementById('messagesButton').addEventListener('click', showMessages);
    
    // 表单提交事件绑定
    document.getElementById('loginForm').addEventListener('submit', handleLogin);
    document.getElementById('registerForm').addEventListener('submit', handleRegister);
    
    // 用户资料相关事件绑定
    document.getElementById('updateEmailForm').addEventListener('submit', function(e) {
        e.preventDefault();
        updateEmail();
    });
    document.getElementById('updatePasswordForm').addEventListener('submit', function(e) {
        e.preventDefault();
        updatePassword();
    });
    
    // 私信相关事件绑定
    document.getElementById('sendMessageForm').addEventListener('submit', function(e) {
        e.preventDefault();
        sendPrivateMessage();
    });
});